package com.roc.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.roc.dao.DaoException;
import com.roc.dao.IAgentDao;
import com.roc.dao.IBaseDao;
import com.roc.dao.IModelDao;
import com.roc.dao.ISQLBaseDao;
import com.roc.dao.agent.IAgentInfoDao;
import com.roc.newPage.IPageDao;
import com.roc.pojo.EsmidinfoMerinfo;
import com.roc.pojo.EsmidinfoTmp;
import com.roc.pojo.MerchantModuleRight;
import com.roc.pojo.MessageSend;
import com.roc.pojo.Operators;
import com.roc.pojo.ProfitModule;
import com.roc.pojo.ProfitPercent;
import com.roc.pojo.ProfitPercentModule;
import com.roc.pojo.ProfitRule;
import com.roc.pojo.ProfitRuleModule;
import com.roc.pojo.TblOrgMain;
import com.roc.service.IAgentService;
import com.roc.service.IMerchantServices;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.MD5Utils;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.DateFormat;
import com.roc.util.constant.MerinfoModule;
import com.roc.util.constant.OperatorsStatus;
import com.roc.util.constant.ProfitModuleStatus;
import com.roc.util.constant.Role;
import com.roc.util.constant.SysLogType;
import com.roc.util.constant.TblBlackInfType;

@Service
@Transactional
public class AgentServiceImpl implements IAgentService {
	static Logger logger = Logger.getLogger(AgentServiceImpl.class);
	@Autowired
	private IAgentDao agentDao;
	@Autowired
	private IAgentInfoDao agentInfoDao;
	@Autowired
	private IBaseDao baseDao;
	@Autowired
	private ISQLBaseDao IbaseDao;
	@Autowired
	private IPageDao pageDao;
	@Autowired
	IModelDao modelDao;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired
	IPowerInfoService powerInfoService;
	/**
	 *录入代理商
	 */
	@Override
	@Transactional(rollbackFor = { ServiceException.class })
	public String issueAgent(Operators op, String opAccount,Operators logingOperators)
			throws ServiceException {

		try {
			Object[] params1 = {op.getAccountNo()};
			// 查询账户是否存在
			Operators ops = (Operators) pageDao
					.createQueryUniqueResult("from Operators o where o.accountNo=?" , params1);
			if (ops != null) {
				throw new ServiceException("账号已存在，请重新分配账号！！！");
			}
			
			op.setStatus(OperatorsStatus.OK.getCode());
			// String pwd=Utils.getpass(10);
			String pwd = Utils.getRandomString();
			op.setPwd(MD5Utils.MD5Encode(pwd));
			Date cDate = new Date();
			String cStr = DateFormatUtils.format(cDate, "yyyyMMdd");
			op.setUpdatePWD(cStr); 

			// 如果录入代理商的角色为代理商，则添加代理商的所属分公司/所属一级代理商/是否直营 默认为当前登录账号的值
			if ( op.getRoleType().equals(Role.AGENT.getCode()) ) {
				op.setCompanyid(logingOperators.getCompanyid());
				op.setOneagentid(logingOperators.getOneagentid());
				op.setDirectFlag(logingOperators.getDirectFlag());
		//		op.setBusinessLicences(logingOperators.getBusinessLicences());
			}
			
			agentDao.editSave(op);
/*
			
			if( logingOperators.getRoleType().equals(Role.SYSTEM.getCode())
					 || logingOperators.getRoleType().equals(Role.O_MANAGER.getCode()) ){

				agentDao.updateSQLQuery("update T_OPERATORS t set t.ONEAGENTID = " + String.valueOf(op.getId()) 
						+ "  where t.ROLE_TYPE = '02' and t.ID='" + op.getId() + "'");
			}*/
			
			String isUseDefModule = op.getIsUseDefModule();
			if(null != isUseDefModule && !isUseDefModule.equals("")){

				// 查询当前默认的模板信息
				ProfitModule bean = modelDao.selDefProfitModuleByAgentId( logingOperators.getId());
				
				String modelId = String.valueOf(bean.getId());
				List<ProfitRuleModule> profitRuleModuleList = modelDao.queryProfitRuleModule(modelId);
				List<ProfitPercentModule> profitPerModuleList = modelDao.queryProfitPerModule(modelId);

				// 添加MCC类别
				for (ProfitRuleModule profitRuleModule : profitRuleModuleList) {
					ProfitRule profitRule = new ProfitRule();
					
					profitRule.setMccTypeCode (profitRuleModule.getMccTypeCode());
					profitRule.setMccTypeName (profitRuleModule.getMccTypeName());
					profitRule.setProfitFee (profitRuleModule.getProfitFee());
					profitRule.setProfitSettleRate (profitRuleModule.getProfitSettleRate());
					profitRule.setDtCreate (profitRuleModule.getDtCreate());
					profitRule.setDtLostmod (profitRuleModule.getDtLastmod());
					profitRule.setMerchantMinFee (profitRuleModule.getMerchantMinFee());
					profitRule.setMaxFee (profitRuleModule.getMaxFee());

					
					profitRule.setAgentId(op.getAccountNo());
					profitRule.setOperators(opAccount);

					// 如果是 云闪付，判断费率是否为0.28
					if ( "05".equals(profitRule.getMccTypeCode() ) ){
						double profitFee = profitRule.getProfitFee() ; 
						double profitSettleRate = profitRule.getProfitSettleRate() ; 
						double merchantMinFee = profitRule.getMerchantMinFee() ; 
						
						if ( profitFee != Constant.FEE_RATE ){
							throw new DaoException("代理申请失败，云闪付 借记卡成本扣率 只能等于 " + Constant.FEE_RATE );
						}
						if ( profitSettleRate != Constant.FEE_RATE ){
							throw new DaoException("代理申请失败，云闪付 贷记卡成本扣率 只能等于 " + Constant.FEE_RATE );
						}
						if ( merchantMinFee != Constant.FEE_RATE ){
							throw new DaoException("代理申请失败，云闪付 贷记卡最低签扣 只能等于 " + Constant.FEE_RATE );
						}
					}
					// 如果是 银联扫码（非优惠），判断费率是否低于0.5025
					if ( "06".equals(profitRule.getMccTypeCode() ) ){
						double profitFee = profitRule.getProfitFee() ; 
						
						if ( profitFee < Constant.UNIONPAY_EVERYDAY_RATE ){
							throw new DaoException("代理申请失败，银联扫码(非优惠) 成本扣率 不能低于 " + Constant.UNIONPAY_EVERYDAY_RATE );
						}
					}
					// 如果是 银联扫码（优惠），判断费率是否低于0.2
					if ( "07".equals(profitRule.getMccTypeCode() ) ){
						double profitFee = profitRule.getProfitFee() ; 
						
						if ( profitFee < Constant.UNIONPAY_UNEVERYDAY_RATE ){
							throw new DaoException("代理申请失败，银联扫码(优惠) 成本扣率 不能低于 " + Constant.UNIONPAY_UNEVERYDAY_RATE );
						}
					}
					// 如果是 支付宝微信扫码，判断费率只能是 0.25-0.35 之间
					if ( "08".equals(profitRule.getMccTypeCode() ) ){
						double profitFee = profitRule.getProfitFee() ; 
						
						if ( profitFee < Constant.MIN_ALIPAY_RATE || profitFee > Constant.MAX_ALIPAY_RATE ){
							throw new DaoException("代理申请失败，支付宝微信扫码 成本扣率 只能是 " + Constant.MIN_ALIPAY_RATE +"-" + Constant.MAX_ALIPAY_RATE + " 之间 " );
						}
					}
					
					agentDao.editSave(profitRule);// add分润规则
				}


				int i = 0;
				// 添加代理商分润比例
				for (ProfitPercentModule profitPercentModule : profitPerModuleList) {
					ProfitPercent profitPercent = new ProfitPercent();

			//		profitPercent.setAgentId (profitPercentModule.getAgentId());
					profitPercent.setLimit_amt (profitPercentModule.getLimitAmt());
					profitPercent.setMax_amt (profitPercentModule.getMaxAmt());
					profitPercent.setPercent (profitPercentModule.getPercent());
			//		profitPercent.setIsEnd (profitPercentModule.getIsEnd());
					
					profitPercent.setAgent_id(op.getAccountNo());
				/*	BigDecimal per = new BigDecimal(profitPercent.getPercent());
					profitPercent.setPercent(per.divide(new BigDecimal(100))
							.toString());*/

					if (i == 0) {
						profitPercent.setIs_end("0");
					} else {
						profitPercent.setIs_end("1");
					}
					if (i == profitPerModuleList.size() - 1) {
						profitPercent.setIs_end("2");
					}
					agentDao.editSave(profitPercent);
					i++;
				
				}
				
			} else {

				// 添加MCC类别
				if (op.getProList() != null && op.getProList().size() > 0) {
					List<ProfitRule> prList = op.getProList();
					for (ProfitRule profitRule : prList) {
						if (profitRule.getId() != null) {
							// 如果是 云闪付，判断费率是否为0.28
							if ( 5 == profitRule.getId() ){
								double profitFee = profitRule.getProfitFee() ; 
								double profitSettleRate = profitRule.getProfitSettleRate() ; 
								double merchantMinFee = profitRule.getMerchantMinFee() ; 
								
								if ( profitFee != Constant.FEE_RATE ){
									throw new ServiceException("代理申请失败，云闪付 借记卡成本扣率 只能等于 " + Constant.FEE_RATE );
								}
								if ( profitSettleRate != Constant.FEE_RATE ){
									throw new ServiceException("代理申请失败，云闪付 贷记卡成本扣率 只能等于 " + Constant.FEE_RATE );
								}
								if ( merchantMinFee != Constant.FEE_RATE ){
									throw new ServiceException("代理申请失败，云闪付 贷记卡最低签扣 只能等于 " + Constant.FEE_RATE );
								}
							}
							// 如果是 银联扫码（非优惠），判断费率是否低于0.5025
							if ( 6 == profitRule.getId() ){
								double profitFee = profitRule.getProfitFee() ; 
								
								if ( profitFee < Constant.UNIONPAY_EVERYDAY_RATE ){
									throw new ServiceException("代理申请失败，银联扫码(非优惠) 成本扣率 不能低于 " + Constant.UNIONPAY_EVERYDAY_RATE );
								}
							}
							// 如果是 银联扫码（优惠），判断费率是否低于0.2
							if ( 7 == profitRule.getId() ){
								double profitFee = profitRule.getProfitFee() ; 
								
								if ( profitFee < Constant.UNIONPAY_UNEVERYDAY_RATE ){
									throw new ServiceException("代理申请失败，银联扫码(优惠) 成本扣率 不能低于 " + Constant.UNIONPAY_UNEVERYDAY_RATE );
								}
							}
							// 如果是 支付宝微信扫码，判断费率只能是 0.25-0.35 之间
							if ( 8 == profitRule.getId() ){
								double profitFee = profitRule.getProfitFee() ; 
								
								if ( profitFee < Constant.MIN_ALIPAY_RATE || profitFee > Constant.MAX_ALIPAY_RATE ){
									throw new ServiceException("代理申请失败，支付宝微信扫码 成本扣率 只能是 " + Constant.MIN_ALIPAY_RATE +"-" + Constant.MAX_ALIPAY_RATE + " 之间 " );
								}
							}
							
							profitRule.setAgentId(op.getAccountNo());
							profitRule.setOperators(opAccount);
							agentDao.editSave(profitRule);// add分润规则
						}
					}
				}
				// 添加代理商分润比例
				if (op.getProfitPerList() != null
						&& op.getProfitPerList().size() > 0) {
					List<ProfitPercent> prList = op.getProfitPerList();
					// 删除空数据
					prList = dealNull(prList);
					int i = 0;
					for (ProfitPercent profitPercent : prList) {
						profitPercent.setAgent_id(op.getAccountNo());
						BigDecimal per = new BigDecimal(profitPercent.getPercent());
						profitPercent.setPercent(per.divide(new BigDecimal(100))
								.toString());

						if (i == 0) {
							profitPercent.setIs_end("0");
						} else {
							profitPercent.setIs_end("1");
						}
						if (i == prList.size() - 1) {
							profitPercent.setIs_end("2");
						}
						agentDao.editSave(profitPercent);
						i++;
					}

				}
			}

			// 添加基本菜单
			for (int i = 0; i < 6; i++) {
				MerchantModuleRight mmr = new MerchantModuleRight();
				mmr.setMerchantNo(op.getAccountNo());
				mmr.setOperators(opAccount);
				if (i == 0) {
					mmr.setModuleCode(MerinfoModule.C_02_M_02.getName());// 商户查询
				} else if (i == 1) {
					mmr.setModuleCode(MerinfoModule.C_04_M_01.getName());// 交易查询
				} else if (i == 2) {
					mmr.setModuleCode(MerinfoModule.C_04_M_02.getName());// 结算查询
				} else if (i == 3) {
					mmr.setModuleCode(MerinfoModule.C_07_M_02.getName());// 终端查询
				} else if (i == 4) {
					mmr.setModuleCode(MerinfoModule.C_03_M_01.getName());// 代理商录入
				} else if (i == 5) {
					mmr.setModuleCode(MerinfoModule.C_03_M_02.getName());// 代理商查询
				}
				agentDao.editSave(mmr);
			}
			//您已开通付临门收单运营平台，您的账号：XXX，您的密码是：XXX，系统的链接地址为：XXXX
			StringBuffer sb = new StringBuffer();
			String mesContent = sb.append("您已开通付临门收单运营平台，您的账号：").append(op.getAccountNo()).append("，您的密码是：" + pwd + "，系统的链接地址为：https://shoudan.freemypay.com:18081/fmposm/login.jsp。").toString();
			logger.info("保存发送短信内容："+mesContent);
			MessageSend ms = new MessageSend();
			ms.setPhoneNumber(op.getMobile());
			ms.setMesContent(mesContent);
			ms.setSendFlag("0");
			ms.setDtCreate(new Date());
			ms.setTimes(0);
			baseDao.editSave(ms);
			logger.info("保存完毕");
			return pwd;
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error("######代理申请失败######", e);
			throw new ServiceException("代理申请失败");
		}
	}

	/**
	 *录入一级代理商
	 */
	@Override
	@Transactional(rollbackFor = { ServiceException.class })
	public String isAddOneAgent(Operators op, String opAccount,Operators logingOperators)
			throws ServiceException {

		try {
			Object[] params1 = {op.getAccountNo()};
			// 查询账户是否存在
			Operators ops = (Operators) pageDao
					.createQueryUniqueResult("from Operators o where o.accountNo=?" , params1);
			if (ops != null) {
				throw new ServiceException("账号已存在，请重新分配账号！！！");
			}
			
			op.setStatus(OperatorsStatus.OK.getCode());
			// String pwd=Utils.getpass(10);
			String pwd = Utils.getRandomString();
			op.setPwd(MD5Utils.MD5Encode(pwd));
			Date cDate = new Date();
			String cStr = DateFormatUtils.format(cDate, "yyyyMMdd");
			op.setUpdatePWD(cStr);
			agentDao.editSave(op);

			// 修改所属一级代理商
			String updSql = "";			
			updSql = " t.ONEAGENTID = " + String.valueOf(op.getId()) ;

			agentDao.updateSQLQuery("update T_OPERATORS t set " + updSql 
					+ "  where t.ID='" + op.getId() + "'");
			/*
			if(logingOperators.getRoleType().equals(Role.AGENT.getCode()) || 
					logingOperators.getRoleType().equals(Role.AGENT_BUSS.getCode())){// 代理商 或 业务员
				Operators loginOps = logingOperators;
				// 如果是业务员，取它的上级代理商
				if ( logingOperators.getRoleType().equals(Role.AGENT_BUSS.getCode()) ){

					loginOps = powerInfoService.loadOperatorsById(logingOperators.getSuperiorId());
				}
				
				int type = getType(loginOps);
				String updSql = "";			
				if(type == 1){// 收单事业部
					updSql = " t.COMPANYID = " + String.valueOf(op.getId());
				}else if(type == 2){// 分公司
					updSql = " t.COMPANYID = " + String.valueOf(loginOps.getId()) 
							+ " , t.ONEAGENTID = " + String.valueOf(op.getId()) ;
				}else if(type == 3 ){// 其他[一级代理商,二级代理,....]
					updSql =  " t.COMPANYID = " + loginOps.getCompanyid() 
							+ " , t.ONEAGENTID = " + loginOps.getOneagentid() 
							;
				}	
			
				agentDao.updateSQLQuery("update T_OPERATORS t set " + updSql 
						+ "  where t.ID='" + op.getId() + "'");
			}*/
			
			String isUseDefModule = op.getIsUseDefModule();
			if(null != isUseDefModule && !isUseDefModule.equals("")){

				// 查询当前默认的模板信息
				ProfitModule bean = modelDao.selDefProfitModuleByAgentId( logingOperators.getId());
				
				String modelId = String.valueOf(bean.getId());
				List<ProfitRuleModule> profitRuleModuleList = modelDao.queryProfitRuleModule(modelId);
				List<ProfitPercentModule> profitPerModuleList = modelDao.queryProfitPerModule(modelId);

				// 添加MCC类别
				for (ProfitRuleModule profitRuleModule : profitRuleModuleList) {
					ProfitRule profitRule = new ProfitRule();
					
				//	profitRule.setId (profitRuleModule.getId());
					profitRule.setMccTypeCode (profitRuleModule.getMccTypeCode());
					profitRule.setMccTypeName (profitRuleModule.getMccTypeName());
					profitRule.setProfitFee (profitRuleModule.getProfitFee());
					profitRule.setProfitSettleRate (profitRuleModule.getProfitSettleRate());
		//			profitRule.setRemark (profitRuleModule.getRemark());
		//			profitRule.setAgentId (profitRuleModule.getAgentId());
					profitRule.setDtCreate (profitRuleModule.getDtCreate());
					profitRule.setDtLostmod (profitRuleModule.getDtLastmod());
				//	profitRule.setOperators (profitRuleModule.getOperators());
				//	profitRule.setParamName1 (profitRuleModule.getParamName1());
				//	profitRule.setParamName2 (profitRuleModule.getParamName2());
					profitRule.setMerchantMinFee (profitRuleModule.getMerchantMinFee());
					profitRule.setMaxFee (profitRuleModule.getMaxFee());

					
					profitRule.setAgentId(op.getAccountNo());
					profitRule.setOperators(opAccount);
					agentDao.editSave(profitRule);// add分润规则
				}


				int i = 0;
				// 添加代理商分润比例
				for (ProfitPercentModule profitPercentModule : profitPerModuleList) {
					ProfitPercent profitPercent = new ProfitPercent();

			//		profitPercent.setAgentId (profitPercentModule.getAgentId());
					profitPercent.setLimit_amt (profitPercentModule.getLimitAmt());
					profitPercent.setMax_amt (profitPercentModule.getMaxAmt());
					profitPercent.setPercent (profitPercentModule.getPercent());
			//		profitPercent.setIsEnd (profitPercentModule.getIsEnd());
					
					profitPercent.setAgent_id(op.getAccountNo());
				/*	BigDecimal per = new BigDecimal(profitPercent.getPercent());
					profitPercent.setPercent(per.divide(new BigDecimal(100))
							.toString());*/

					if (i == 0) {
						profitPercent.setIs_end("0");
					} else {
						profitPercent.setIs_end("1");
					}
					if (i == profitPerModuleList.size() - 1) {
						profitPercent.setIs_end("2");
					}
					agentDao.editSave(profitPercent);
					i++;
				
				}
				
			} else {

				// 添加MCC类别
				if (op.getProList() != null && op.getProList().size() > 0) {
					List<ProfitRule> prList = op.getProList();
					for (ProfitRule profitRule : prList) {
						if (profitRule.getId() != null) {
							// 如果是 云闪付，判断费率是否为0.28
							if ( 5 == profitRule.getId() ){
								double profitFee = profitRule.getProfitFee() ; 
								double profitSettleRate = profitRule.getProfitSettleRate() ; 
								double merchantMinFee = profitRule.getMerchantMinFee() ; 
								
								if ( profitFee != Constant.FEE_RATE ){
									throw new ServiceException("代理申请失败，云闪付 借记卡成本扣率 只能等于 " + Constant.FEE_RATE );
								}
								if ( profitSettleRate != Constant.FEE_RATE ){
									throw new ServiceException("代理申请失败，云闪付 贷记卡成本扣率 只能等于 " + Constant.FEE_RATE );
								}
								if ( merchantMinFee != Constant.FEE_RATE ){
									throw new ServiceException("代理申请失败，云闪付 贷记卡最低签扣 只能等于 " + Constant.FEE_RATE );
								}
							}
							// 如果是 银联扫码（非优惠），判断费率是否低于0.5025
							if ( 6 == profitRule.getId() ){
								double profitFee = profitRule.getProfitFee() ; 
								
								if ( profitFee < Constant.UNIONPAY_EVERYDAY_RATE ){
									throw new ServiceException("代理申请失败，银联扫码(非优惠) 成本扣率 不能低于 " + Constant.UNIONPAY_EVERYDAY_RATE );
								}
							}
							// 如果是 银联扫码（优惠），判断费率是否低于0.2
							if ( 7 == profitRule.getId() ){
								double profitFee = profitRule.getProfitFee() ; 
								
								if ( profitFee < Constant.UNIONPAY_UNEVERYDAY_RATE ){
									throw new ServiceException("代理申请失败，银联扫码(优惠) 成本扣率 不能低于 " + Constant.UNIONPAY_UNEVERYDAY_RATE );
								}
							}
							// 如果是 支付宝微信扫码，判断费率只能是 0.25-0.35 之间
							if ( 8 == profitRule.getId() ){
								double profitFee = profitRule.getProfitFee() ; 
								
								if ( profitFee < Constant.MIN_ALIPAY_RATE || profitFee > Constant.MAX_ALIPAY_RATE ){
									throw new ServiceException("代理申请失败，支付宝微信扫码 成本扣率 只能是 " + Constant.MIN_ALIPAY_RATE +"-" + Constant.MAX_ALIPAY_RATE + " 之间 " );
								}
							}
							
							profitRule.setAgentId(op.getAccountNo());
							profitRule.setOperators(opAccount);
							agentDao.editSave(profitRule);// add分润规则
						}
					}
				}
				// 添加代理商分润比例
				if (op.getProfitPerList() != null
						&& op.getProfitPerList().size() > 0) {
					List<ProfitPercent> prList = op.getProfitPerList();
					// 删除空数据
					prList = dealNull(prList);
					int i = 0;
					for (ProfitPercent profitPercent : prList) {
						profitPercent.setAgent_id(op.getAccountNo());
						BigDecimal per = new BigDecimal(profitPercent.getPercent());
						profitPercent.setPercent(per.divide(new BigDecimal(100))
								.toString());

						if (i == 0) {
							profitPercent.setIs_end("0");
						} else {
							profitPercent.setIs_end("1");
						}
						if (i == prList.size() - 1) {
							profitPercent.setIs_end("2");
						}
						agentDao.editSave(profitPercent);
						i++;
					}

				}
			}

			// 添加基本菜单
			for (int i = 0; i < 6; i++) {
				MerchantModuleRight mmr = new MerchantModuleRight();
				mmr.setMerchantNo(op.getAccountNo());
				mmr.setOperators(opAccount);
				if (i == 0) {
					mmr.setModuleCode(MerinfoModule.C_02_M_02.getName());// 商户查询
				} else if (i == 1) {
					mmr.setModuleCode(MerinfoModule.C_04_M_01.getName());// 交易查询
				} else if (i == 2) {
					mmr.setModuleCode(MerinfoModule.C_04_M_02.getName());// 结算查询
				} else if (i == 3) {
					mmr.setModuleCode(MerinfoModule.C_07_M_02.getName());// 终端查询
				} else if (i == 4) {
					mmr.setModuleCode(MerinfoModule.C_03_M_01.getName());// 代理商录入
				} else if (i == 5) {
					mmr.setModuleCode(MerinfoModule.C_03_M_02.getName());// 代理商查询
				}
				agentDao.editSave(mmr);
			}
			//您已开通付临门收单运营平台，您的账号：XXX，您的密码是：XXX，系统的链接地址为：XXXX
			StringBuffer sb = new StringBuffer();
			String mesContent = sb.append("您已开通付临门收单运营平台，您的账号：").append(op.getAccountNo()).append("，您的密码是：" + pwd + "，系统的链接地址为：https://shoudan.freemypay.com:18081/fmposm/login.jsp。").toString();
			logger.info("保存发送短信内容："+mesContent);
			MessageSend ms = new MessageSend();
			ms.setPhoneNumber(op.getMobile());
			ms.setMesContent(mesContent);
			ms.setSendFlag("0");
			ms.setDtCreate(new Date());
			ms.setTimes(0);
			baseDao.editSave(ms);
			logger.info("保存完毕");
			return pwd;
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error("######代理申请失败######", e);
			throw new ServiceException("代理申请失败");
		}
	}
	@Transactional(rollbackFor = { ServiceException.class })
	public void editAgent(Operators op, Operators oldOp,
			Operators logingOperators) throws ServiceException {
		// 查询账户是否存在
		try {
			if (oldOp != null) {// 数据库代理商信息不为空
				// 第一个参数为页面绑定的对象
				saveEditAgentValue(op, oldOp, logingOperators);
				logger.info("操作员【" + logingOperators.getAccountNo()
						+ "】,补全代理商【" + oldOp.getAccountNo() + "】信息成功");
				baseDao.addSyslog(SysLogType.AGENT_UPDATE.getCode(),
						SysLogType.AGENT_UPDATE.getName(), logingOperators
								.getAccountNo(), "操作员"
								+ logingOperators.getAccountNo() + "【"
								+ oldOp.getAccountNo() + "】代理商信息成功");
			} else {
				logger.info("######代理商补全资料失败,代理商不存在######");
			}
		} catch (DaoException e) {
			logger.error("######代理商补全资料失败######", e);
			throw new ServiceException("代理商补全资料失败!");
		}
	}

	/**
	 * 
	 * @param op
	 * @param oper
	 * @param logingOperators
	 * @throws DaoException
	 */
	private void saveEditAgentValue(Operators op, Operators oldOP,
			Operators logingOperators) throws DaoException {
		setOperatorsProtertyValue(op, oldOP, logingOperators);

		agentDao.editUpdate(oldOP);
		
		// 通过代理商id删除代理商分润规则
		agentInfoDao.deleteProfitRuleByAgentId(oldOP.getAccountNo() + "");
		// 通过代理商id删除代理商分润比例
		agentInfoDao.deleteProfitPerByAgentId(oldOP.getAccountNo() + "");
		
		String opAccount=logingOperators.getAccountNo();
		
		String isUseDefModule = op.getIsUseDefModule();
		if(null != isUseDefModule && !isUseDefModule.equals("")){
			// 查询当前默认的模板信息
			ProfitModule bean = modelDao.selDefProfitModuleByAgentId( logingOperators.getId());
			
			String modelId = String.valueOf(bean.getId());
			List<ProfitRuleModule> profitRuleModuleList = modelDao.queryProfitRuleModule(modelId);
			List<ProfitPercentModule> profitPerModuleList = modelDao.queryProfitPerModule(modelId);

			// 添加MCC类别
			for (ProfitRuleModule profitRuleModule : profitRuleModuleList) {
				ProfitRule profitRule = new ProfitRule();
				
				profitRule.setMccTypeCode (profitRuleModule.getMccTypeCode());
				profitRule.setMccTypeName (profitRuleModule.getMccTypeName());
				profitRule.setProfitFee (profitRuleModule.getProfitFee());
				profitRule.setProfitSettleRate (profitRuleModule.getProfitSettleRate());
				profitRule.setDtCreate (new Date());
				profitRule.setDtLostmod (new Date());
				profitRule.setMerchantMinFee (profitRuleModule.getMerchantMinFee());
				profitRule.setMaxFee (profitRuleModule.getMaxFee());

				profitRule.setAgentId(oldOP.getAccountNo());
				profitRule.setOperators(opAccount);

				// 如果是 云闪付，判断费率是否为0.28
				if ( "05".equals(profitRule.getMccTypeCode() ) ){
					double profitFee = profitRule.getProfitFee() ; 
					double profitSettleRate = profitRule.getProfitSettleRate() ; 
					double merchantMinFee = profitRule.getMerchantMinFee() ; 
					
					if ( profitFee != Constant.FEE_RATE ){
						throw new DaoException("代理申请失败，云闪付 借记卡成本扣率 只能等于 " + Constant.FEE_RATE );
					}
					if ( profitSettleRate != Constant.FEE_RATE ){
						throw new DaoException("代理申请失败，云闪付 贷记卡成本扣率 只能等于 " + Constant.FEE_RATE );
					}
					if ( merchantMinFee != Constant.FEE_RATE ){
						throw new DaoException("代理申请失败，云闪付 贷记卡最低签扣 只能等于 " + Constant.FEE_RATE );
					}
				}
				// 如果是 银联扫码（非优惠），判断费率是否低于0.5025
				if ( "06".equals(profitRule.getMccTypeCode() ) ){
					double profitFee = profitRule.getProfitFee() ; 
					
					if ( profitFee < Constant.UNIONPAY_EVERYDAY_RATE ){
						throw new DaoException("代理申请失败，银联扫码(非优惠) 成本扣率 不能低于 " + Constant.UNIONPAY_EVERYDAY_RATE );
					}
				}
				// 如果是 银联扫码（优惠），判断费率是否低于0.2
				if ( "07".equals(profitRule.getMccTypeCode() ) ){
					double profitFee = profitRule.getProfitFee() ; 
					
					if ( profitFee < Constant.UNIONPAY_UNEVERYDAY_RATE ){
						throw new DaoException("代理申请失败，银联扫码(优惠) 成本扣率 不能低于 " + Constant.UNIONPAY_UNEVERYDAY_RATE );
					}
				}
				// 如果是 支付宝微信扫码，判断费率只能是 0.25-0.35 之间
				if ( "08".equals(profitRule.getMccTypeCode() ) ){
					double profitFee = profitRule.getProfitFee() ; 
					
					if ( profitFee < Constant.MIN_ALIPAY_RATE || profitFee > Constant.MAX_ALIPAY_RATE ){
						throw new DaoException("代理申请失败，支付宝微信扫码 成本扣率 只能是 " + Constant.MIN_ALIPAY_RATE +"-" + Constant.MAX_ALIPAY_RATE + " 之间 " );
					}
				}
				
				agentDao.editSave(profitRule);// add分润规则
			}


			int i = 0;
			// 添加代理商分润比例
			for (ProfitPercentModule profitPercentModule : profitPerModuleList) {
				ProfitPercent profitPercent = new ProfitPercent();

		//		profitPercent.setAgentId (profitPercentModule.getAgentId());
				profitPercent.setLimit_amt (profitPercentModule.getLimitAmt());
				profitPercent.setMax_amt (profitPercentModule.getMaxAmt());
				profitPercent.setPercent (profitPercentModule.getPercent());
		//		profitPercent.setIsEnd (profitPercentModule.getIsEnd());
				
				profitPercent.setAgent_id(oldOP.getAccountNo());
			/*	BigDecimal per = new BigDecimal(profitPercent.getPercent());
				profitPercent.setPercent(per.divide(new BigDecimal(100))
						.toString());*/

				if (i == 0) {
					profitPercent.setIs_end("0");
				} else {
					profitPercent.setIs_end("1");
				}
				if (i == profitPerModuleList.size() - 1) {
					profitPercent.setIs_end("2");
				}
				agentDao.editSave(profitPercent);
				i++;
			
			}
			
		} else {
			// 添加MCC类别
			if (op.getProList() != null && op.getProList().size() > 0) {
				List<ProfitRule> prList = op.getProList();
				for (ProfitRule profitRule : prList) {
					if (profitRule.getId() != null) {
						// 如果是 云闪付，判断费率是否为0.28
						if ( 5 == profitRule.getId() ){
							double profitFee = profitRule.getProfitFee() ; 
							double profitSettleRate = profitRule.getProfitSettleRate() ; 
							double merchantMinFee = profitRule.getMerchantMinFee() ; 
							
							if ( profitFee != Constant.FEE_RATE ){
								throw new DaoException("代理申请失败，云闪付 借记卡成本扣率 只能等于 " + Constant.FEE_RATE );
							}
							if ( profitSettleRate != Constant.FEE_RATE ){
								throw new DaoException("代理申请失败，云闪付 贷记卡成本扣率 只能等于 " + Constant.FEE_RATE );
							}
							if ( merchantMinFee != Constant.FEE_RATE ){
								throw new DaoException("代理申请失败，云闪付 贷记卡最低签扣 只能等于 " + Constant.FEE_RATE );
							}
						}
						// 如果是 银联扫码（非优惠），判断费率是否低于0.5025
						if ( 6 == profitRule.getId() ){
							double profitFee = profitRule.getProfitFee() ; 
							
							if ( profitFee < Constant.UNIONPAY_EVERYDAY_RATE ){
								throw new DaoException("代理申请失败，银联扫码(非优惠) 成本扣率 不能低于 " + Constant.UNIONPAY_EVERYDAY_RATE );
							}
						}
						// 如果是 银联扫码（优惠），判断费率是否低于0.2
						if ( 7 == profitRule.getId() ){
							double profitFee = profitRule.getProfitFee() ; 
							
							if ( profitFee < Constant.UNIONPAY_UNEVERYDAY_RATE ){
								throw new DaoException("代理申请失败，银联扫码(优惠) 成本扣率 不能低于 " + Constant.UNIONPAY_UNEVERYDAY_RATE );
							}
						}
						// 如果是 支付宝微信扫码，判断费率只能是 0.25-0.35 之间
						if ( 8 == profitRule.getId() ){
							double profitFee = profitRule.getProfitFee() ; 
							
							if ( profitFee < Constant.MIN_ALIPAY_RATE || profitFee > Constant.MAX_ALIPAY_RATE ){
								throw new DaoException("代理申请失败，支付宝微信扫码 成本扣率 只能是 " + Constant.MIN_ALIPAY_RATE +"-" + Constant.MAX_ALIPAY_RATE + " 之间 " );
							}
						}
						
						profitRule.setAgentId(oldOP.getAccountNo());
						profitRule.setOperators(opAccount);
						agentDao.editSave(profitRule);// add分润规则
					}
				}
			}
			// 添加代理商分润比例
			if (op.getProfitPerList() != null
					&& op.getProfitPerList().size() > 0) {
				List<ProfitPercent> prList = op.getProfitPerList();
				// 删除空数据
				prList = dealNull(prList);
				int i = 0;
				for (ProfitPercent profitPercent : prList) {
					profitPercent.setAgent_id(oldOP.getAccountNo());
					BigDecimal per = new BigDecimal(profitPercent.getPercent());
					profitPercent.setPercent(per.divide(new BigDecimal(100))
							.toString());

					if (i == 0) {
						profitPercent.setIs_end("0");
					} else {
						profitPercent.setIs_end("1");
					}
					if (i == prList.size() - 1) {
						profitPercent.setIs_end("2");
					}
					agentDao.editSave(profitPercent);
					i++;
				}

			}
			
		}
	}

	/**
	 * 
	 * @param from
	 * @param target
	 * @param logingOperators
	 */
	private void setOperatorsProtertyValue(Operators from, Operators target,
			Operators logingOperators) {
		target.setAddress(from.getAddress());
		target.setAgentName(from.getAgentName());
		target.setRealName(from.getRealName());
		target.setBankAcctName(from.getBankAcctName());
		target.setBankAcctNo(from.getBankAcctNo());
		target.setBankDeposit(from.getBankDeposit());
		target.setBusinessLicences(from.getBusinessLicences());
		target.setTaxRegistrationCertificate(from.getTaxRegistrationCertificate());
		target.setBusinessPerson(from.getBusinessPerson());
		target.setBusinessPhone(from.getBusinessPhone());
		target.setBusinessScope(from.getBusinessScope());
//		target.setOrganizationCode(from.getOrganizationCode());
		target.setTelphone(from.getTelphone());
		target.setCardNo(from.getCardNo());
		target.setCardType(from.getCardType());
		target.setDtLostmod(new Date());
		target.setEmail(from.getEmail());
		target.setFlag(from.getFlag());
		target.setMerLevelDesc(from.getMerLevelDesc());
		target.setMobile(from.getMobile());
		target.setOperators(logingOperators.getAccountNo());
		target.setQq(from.getQq());
		target.setRealName(from.getRealName());
		target.setRemark(from.getRemark());
		target.setSex(from.getSex());
		target.setShortName(from.getShortName());
		target.setZipeCode(from.getZipeCode());
		target.setAreaCode(from.getAreaCode());
		target.setBank_no(from.getBank_no());
		target.setGroupCd(from.getGroupCd());
		/*
		target.setStatus(from.getStatus());*/
	}

	// 商户终审生成操作员并且添加权限 停用
	@Override
	public void addOperators(Operators op, EsmidinfoTmp tmp,
			EsmidinfoMerinfo esMer, String mid) throws ServiceException {
		// 添加操作员
		try {
			Operators ops = new Operators();
			ops.setAccountNo(mid);
			ops.setRealName(tmp.getMerBrName());
			String pwd = MD5Utils.MD5Encode(op.getPwd());
			ops.setPwd(pwd);
			DateFormat df = DateFormat.ZH_DEL_ALL;
			Date newDate = df.toDate(Constance.formateDateTime());
			newDate.setYear(newDate.getYear() + 1);
			ops.setValidEndDate(df.toString(newDate));// 操作员有效期
			ops.setValidStartDate(Constance.formateDateTime());// 有效期开始日期
			ops.setMobile(esMer.getPersonalPhone());// 法人手机号
			ops.setOrgCode(tmp.getBelongBranch());// 机构
			ops.setStatus(OperatorsStatus.OK.getCode());// 状态
			ops.setSuperiorId(op.getId());// 父类id
			ops.setOperators(op.getAccountNo());// op
			ops.setRoleType(Role.MERCHANT.getCode());// 角色类别
			ops.setFlag(op.getFlag());

			String time = "";
			Date dt = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			time = sdf.format(dt);
			ops.setUpdatePWD(time);
			// ops.setRealName(mer.getMerName());
			ops.setSex("1");
			agentDao.editSave(ops);
			// 添加商户权限（初始4个权限）
			for (int i = 0; i < 4; i++) {
				MerchantModuleRight mmr = new MerchantModuleRight();
				mmr.setMerchantNo(mid);
				mmr.setOperators(op.getAccountNo());
				/*if (i == 0) {
					mmr.setModuleCode(MerinfoModule.C_02_M_02.getName());// 商户查询
				} else if (i == 1) {
					mmr.setModuleCode(MerinfoModule.C_04_M_01.getName());// 交易查询
				} else if (i == 2) {
					mmr.setModuleCode(MerinfoModule.C_04_M_02.getName());// 历史交易查询
				} else if (i == 3) {
					mmr.setModuleCode(MerinfoModule.C_07_M_02.getName());// 终端查询
				}*/
				agentDao.editSave(mmr);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("######商户操作员添加失败######", e);
			throw new ServiceException("商户操作员添加失败");
		}
	}

	@Override
	public List<ProfitRule> queryProfitRule(String id) throws ServiceException {
		List<ProfitRule> ruleList = new ArrayList<ProfitRule>();
		try {
			Object[] params1 = {id};
			List<?> lists = pageDao.queryAll("from ProfitRule p where p.agentId = ? order by p.mccTypeCode", params1);

			if(null != lists && lists.size() > 0){
				
				for (Object object : lists) {
					ProfitRule profitRule = (ProfitRule)object;
					ruleList.add(profitRule);
				}
			}
			
		//	ruleList = agentInfoDao.queryProfitRule(id);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("######代理商分润规则查询失败######", e);
		}
		return ruleList;
	}

	@Override
	public void deleteProfitRuleByAgentId(String agentId)
			throws ServiceException {
		try {
			agentInfoDao.deleteProfitRuleByAgentId(agentId);
			logger.info("######代理商分润规则删除,agentid:" + agentId);
		} catch (DaoException e) {
			e.printStackTrace();
			logger.error("######代理商分润规则删除失败######", e);
		}
	}

	/**
	 * 查询代理商的可用的MCC,返回map结构
	 * 
	 * @param id
	 * @return
	 * @throws ServiceException
	 */
	@Override
	public Map<String, String> getMccArray4Agent(String id, String roleType)
			throws ServiceException {
		HashMap<String, String> map = new HashMap<String, String>();

		if (!Role.AGENT.getCode().equals(roleType) && !Role.O_MANAGER.getCode().equals(roleType)) {
			return ConfigProperties.getMccTypeProperties();
		}

		List<ProfitRule> list = queryProfitRule(id);

		for (ProfitRule pro : list) {
			map.put(pro.getMccTypeCode(), pro.getMccTypeName());
		}

		return map;
	}

	/**
	 * 查询代理商分润比例MAP
	 * 
	 * @param id
	 * @return
	 * @throws ServiceException
	 */
	@Override
	public Map<String, String> queryProfitPerMap(String agentId)
			throws ServiceException {

		return null;
	}

	@Override
	public List<ProfitPercent> queryProfitPer(String agentId)
			throws ServiceException {
		List<ProfitPercent> ruleList = new ArrayList<ProfitPercent>();
		try {

			Object[] params1 = {agentId};
			List<?> lists = pageDao.queryAll("from ProfitPercent p where p.agent_id = ? order by p.id ", params1);

			if(null != lists && lists.size() > 0){
				
				for (Object object : lists) {
					ProfitPercent profitPercent = (ProfitPercent)object;
					ruleList.add(profitPercent);
				}
			}
			
			
		//	ruleList = agentInfoDao.queryProfitPer(agentId);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("######代理商分润比例查询失败######", e);
		}
		return ruleList;
	}

	public List<ProfitPercent> dealNull(List<ProfitPercent> prList) {
		List<ProfitPercent> newList = new ArrayList<ProfitPercent>();
		for (ProfitPercent per : prList) {
			if (!"".equals(per.getPercent().trim()) && per.getPercent() != null) {
				newList.add(per);
			}
		}
		return newList;

	}

	@Override
	public Map<String, String> queryAgentDirectMap(String agentId)
			throws ServiceException {		
		Map<String, String> agentMap = new HashMap<String,String>();
		try {
		String sql="select level,id,real_name from t_operators op where op.role_type='03' and op.id="+agentId+" start with op.id=40001 connect by prior op.id= op.supri_id order by level";
		Object objExist=baseDao.createSQLQueryUniqueResult(sql);
		if(objExist!=null)//若为空即不为收单事业部子代理商
		{
			sql="select max(level) from t_operators op where op.role_type='03' start with op.id="+agentId+" connect by op.id=prior op.supri_id order by level";
			Object obj=baseDao.createSQLQueryUniqueResult(sql);
			int level=Integer.valueOf(String.valueOf(obj));
			if(level==1)
			{
				if(agentId.equals("40001"))
				{
					return null;
				}
			}
			/*else if(level==2)
			{
				sql="select level,id,real_name from t_operators op where op.role_type='03' and level="+(level-1)+" start with op.id="+agentId+" connect by op.id=prior op.supri_id order by level";
				List<Object> list=IbaseDao.queryAll(sql);
				if(list.size()==1)
				{
					Object[] object=(Object[]) list.get(0);
					agentMap.put("agentId", String.valueOf(object[1]));
					return agentMap;
				}
			}*/
			/*else if(level==3)
			{
				sql="select level,id,real_name from t_operators op where op.role_type='03' and (level="+(level-2)+" or level="+(level-1)+") start with op.id="+agentId+" connect by op.id=prior op.supri_id order by level";
				List<Object> list=IbaseDao.queryAll(sql);
				if(list.size()==2)
				{
					Object[] object1=(Object[]) list.get(0);
					Object[] object2=(Object[]) list.get(1);
					agentMap.put("directId", String.valueOf(object1[1]));
					agentMap.put("agentId", String.valueOf(object2[1]));
					return agentMap;
				}
			}*/
			else if(level>=2)
			{
				sql="select id,real_name from t_operators op where op.role_type='03' and op.id="+agentId+" ";
				List<Object> list=IbaseDao.queryAll(sql);
				if(list.size()==1)
				{
					Object[] object=(Object[]) list.get(0);
					agentMap.put("agentId", String.valueOf(object[0]));
					agentMap.put("agentName", String.valueOf(object[1]));
					if(level>2)
					{
						agentMap.put("flag", "agent");
					}						
					return agentMap;
				}
			}
		}		
			logger.info("该代理商所属错误!!!");
			agentMap.put("msg", "error");
		} catch (DaoException e) {
			logger.info("加载代理商信息失败!!!");
			e.printStackTrace();
		}
		return agentMap;
	}

	public int getType(Operators logingOperators) throws ServiceException {
		int type = 0;
	//	取系统管理员id
		String supId = Constant.ADMIN_ID;
		if(null != logingOperators.getSuperiorId() 
				&&  String.valueOf(logingOperators.getSuperiorId()).equals(supId)){
			type = 1;
		}
		if(type == 0){
			/*if(null != logingOperators.getCompanyid() && !logingOperators.getCompanyid().equals("")
							&& logingOperators.getCompanyid().equals(String.valueOf(logingOperators.getId()))){
				// 分公司
				type = 2;
			}else */if(null != logingOperators.getCompanyid() && !logingOperators.getCompanyid().equals("")
					&& null != logingOperators.getOneagentid()  
					&& !logingOperators.getOneagentid().equals("")
					){// 其他[一级代理商,二级代理,....]
				type = 3;
			}
		}
		return type;
	}

	@Override
	public List<TblOrgMain> queryOrgMainListByArea(String areaId) throws ServiceException {
		List<TblOrgMain> operatorList = new ArrayList<TblOrgMain>();
		try {
			List<?> lists = new ArrayList();
			Object[] params = {areaId};
			lists = pageDao.queryAll("from TblOrgMain p where p.status=1 and p.areaId = ? and p.superId=48502000 order by p.id desc", params);
			if(null != lists && lists.size() > 0){
				for (Object object : lists) {
					TblOrgMain operators = (TblOrgMain)object;
					operatorList.add(operators);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("######直属代理商查询失败######", e);
		}
		return operatorList;
	}

	@Override
	public List<Operators> queryOperatorListBySupId(String agentId)
			throws ServiceException {
		List<Operators> operatorList = new ArrayList<Operators>();
		try {
			List<?> lists = new ArrayList();
			Object[] params = {Long.parseLong(agentId)};
			lists = pageDao.queryAll("from Operators p where p.roleType=03 and p.superiorId=? and p.status=00 order by p.id desc", params);
			if(null != lists && lists.size() > 0){
				for (Object object : lists) {
					Operators operators = (Operators)object;
					operatorList.add(operators);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("######直属代理商查询失败######", e);
		}
		return operatorList;
	}

	@Override
	public List<TblOrgMain> queryOrgMainListByOrg()
			throws ServiceException {
		List<TblOrgMain> operatorList = new ArrayList<TblOrgMain>();
		try {
			Object[] params = {"48502000"};
			List<?> lists = pageDao.queryAll("from TblOrgMain p where p.status=1 and p.superId=? order by p.id desc",params);
			if(null != lists && lists.size() > 0){
				for (Object object : lists) {
					TblOrgMain operators = (TblOrgMain)object;
					operatorList.add(operators);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("######收单机构查询机构查询失败######", e);
		}
		return operatorList;
	}
	

	@Override
	public int selectBlackInfoByType(String blackType,String blackNum) throws ServiceException {		
		int count = 0;
		try {
			count = agentInfoDao.selectBlackInfoByType(blackType, blackNum);
		} catch (DaoException e) {
			logger.info("校验" + TblBlackInfType.getName(blackType) + "-黑名单信息失败!!!" );
			e.printStackTrace();
		}
		return count;
	}
	
	
	
}
